package app

import (
	"gitee.com/tangrx/go-admin/utils/session"
	"github.com/gin-gonic/gin"
	"log"
	"strings"
)

const GETUSERINFO string = "TokenUserInfo"

func TokenErrorAbort(c *gin.Context, code string, message string) {
	c.JSON(200,
		gin.H{"status": code,
			"msg": message,
		})
	c.Abort()
}

// Token中间件
func TokenMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		log.Println(c.Request.URL.Path)
		if strings.ToLower(c.Request.URL.Path) == "/auth/login" || strings.ToLower(c.Request.URL.Path) == "/auth/code" {

			c.Next()
			return
		}
		token := c.Request.Header.Get("Sx-Token")
		// log.Println("header:", c.Request.Header)
		log.Println("token:", token)
		if token == "" {
			TokenErrorAbort(c, "401", "登录token有误，请重新登录")
			return
		}
		var user map[string]interface{}
		err := session.GSession(token, &user)
		if err != nil {
			log.Println("error:", err)
			TokenErrorAbort(c, "402", "登录token有误，请重新登录")
			return
		} else {
			c.Set(GETUSERINFO, user) // 保持用户信息
		}
		c.Next()

	}
}
